package com.omazan.db;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;

import com.omazan.db.models.Employee;
import com.omazan.utils.OmazanException;

public class HandleEmployees {

	public Employee readEmployeeFromDBUsingId(int id) throws OmazanException {

		Employee employee = null;
		try {
			SessionFactory sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();

			// get new session
			Session session = sessionFactory.openSession();
			session.beginTransaction();

			employee = (Employee) session.get(Employee.class, id);
			return employee;
		} catch (HibernateException e) {

			e.printStackTrace();
			return null;

		}

	}

	@SuppressWarnings("unchecked")
	public List<Employee> readAllEmployeesFromDB() throws OmazanException {

		List<Employee> listOfEmployees = new ArrayList<Employee>();
		Session session = null;

		try {

			session = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation().openSession();

			Query query = session.createQuery("from Employee")
					.setResultTransformer(
							CriteriaSpecification.DISTINCT_ROOT_ENTITY);

			listOfEmployees = (List<Employee>) query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return listOfEmployees;
	}

	public boolean insertEmployee(Employee obj) throws OmazanException {

		try {

			SessionFactory sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();

			// get new session
			Session session = sessionFactory.openSession();
			session.beginTransaction();

			session.save(obj);
			session.getTransaction().commit();
			session.close();
			return true;

		} catch (HibernateException e) {

			e.printStackTrace();
			return false;

		}

	}

	public boolean deleteUsingId(int id) {

		SessionFactory sessionFactory;
		try {
			sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			Employee employee = readEmployeeFromDBUsingId(id);
			session.delete(employee);
			session.getTransaction().commit();

		} catch (OmazanException e) {

			e.printStackTrace();
			return false;
		}

		return true;
	}
}
